// src/views/speech/index.jsx
import { useState } from 'react';
import './index.css';
import Recorder from '../../component/recorder';
import { Input, } from 'antd';
import HistoryDrawer from '../../component/drawer';

function SpeechView() {
  const [text, setText] = useState('');
  const [transcription, setTranscription] = useState('');
  const [score, setScore] = useState(0);
  const [errors, setErrors] = useState([]);

  const handleTextChange = (e) => {
    setText(e.target.value);
  };

  const handleTranscriptionComplete = (transcribedText) => {
    console.log('Transcription received:', transcribedText); 
    setTranscription(transcribedText.text); // 访问并设置文本属性

    // 这里调用评分和错误计算的逻辑
    calculateScoreAndErrors(text, transcribedText.text); // 使用 transcribedText.text
};

const calculateScoreAndErrors = (originalText, transcribedText) => {
  // 简单的评分和错误标注逻辑
  let score = 0;
  const errors = [];
  const originalWords = originalText.split(' '); // 原始文本分割为单词
  const transcribedWords = transcribedText.split(' '); // 转录文本分割为单词

  for (let i = 0; i < originalWords.length; i++) {
      if (i < transcribedWords.length && originalWords[i] === transcribedWords[i]) {
          score++;
      } else {
          errors.push({ index: i, word: originalWords[i] });
      }
  }

  score = (score / originalWords.length) * 100; // 计算评分
  setScore(score);
  setErrors(errors);
};


  return (
    <div className="App" >
      <h1>Voice Transcription and Correction</h1>
      <div>
        <Input type="text" value={text} onChange={handleTextChange} style={{ 
                                                                            width: '60%',
                                                                            marginTop : '400px' }} />
      </div>
      <HistoryDrawer />
      <div>
        <Recorder onTranscriptionComplete={handleTranscriptionComplete} />
        {transcription && (
          <div>
            <h2>Transcription:</h2>
            <p>{transcription}</p> 
            <h2>Score: {score.toFixed(2)}%</h2>
            <h2>Errors:</h2>
            <ul>
              {errors.map((error, index) => (
                <li key={index}>
                  Word at index {error.index}: {error.word}
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}

export default SpeechView;